﻿using System;
using System.Collections.Generic;
using System.Linq;
using Actya.Core.SiteStructure;

namespace Actya.Core.Content
{
	/// <summary>
	/// Content for different regions. The key corresponds with the name of the content region, defined in the layout.
	/// </summary>
	public class MultiRegionContent : ContentBase
	{
		/// <summary>
		/// Content for sub-regions.
		/// </summary>
		public Dictionary<string, string> Content { get; private set; }

		public MultiRegionContent()
		{
			this.Content = new Dictionary<string, string>();
		}

		/// <summary>
		/// Gets a textual representation of the content. 
		/// </summary>
		public override string ContentAsText
		{
			get
			{
				var contentAsText = String.Empty;
				foreach (var contentByRegion in Content)
				{
					contentAsText += " " + contentByRegion.Value;
				}
				return contentAsText;
			}
		}

		/// <summary>
		/// Initialize content for the given theme.
		/// </summary>
		/// <param name="theme"></param>
		/// <returns></returns>
		public override IContent InitializeForTheme(Theme theme)
		{
			ApplyContentRegions(theme.ContentRegions);
			return this;
		}

		public override IContent SanitizeContent(Func<string, string> sanitize)
		{
			var keys = Content.Keys.ToArray();
			foreach (var contentKey in keys)
			{
				Content[contentKey] = sanitize(Content[contentKey]);
			}
			return this;
		}

		private void ApplyContentRegions(string[] contentRegions)
		{
			if (contentRegions != null && contentRegions.Length > 0)
			{
				foreach (var contentRegion in contentRegions)
				{
					if (!this.Content.ContainsKey(contentRegion))
					{
						this.Content.Add(contentRegion, String.Empty);
					}
				}
			}
		}

		/// <summary>
		/// Sets the given content in the first content region.
		/// </summary>
		/// <param name="contentText"></param>
		public void SetFirstRegionContent(string contentText)
		{
			if (this.Content.Any())
			{
				this.Content[this.Content.Keys.First()] = contentText;
			}
		}
	}
}
